#include "stdafx.h"
#include "libzip.h"
#include "unzip.h"
#include "zip.h"


libzip::libzip(void)
{
	m_hz = NULL;
	m_pFileBuffer = NULL;
}

libzip::~libzip(void)
{
	close();
}

void libzip::close(void)
{
	if (m_hz) {
		CloseZip(m_hz);
		m_hz = NULL;
	}
	if (m_pFileBuffer) {
		delete[] m_pFileBuffer;
		m_pFileBuffer = NULL;
	}
}

BOOL libzip::load(BYTE* buffer, int len)
{
	m_pFileBuffer = new BYTE[len];
	memcpy(m_pFileBuffer, buffer, len);
	m_hz = OpenZip(m_pFileBuffer, len, NULL);
	return TRUE;
}

BOOL libzip::open(CString sFilePath)
{
	CFile fileZip;
	if (! fileZip.Open(sFilePath, CFile::modeReadWrite)) {
		return FALSE;
	}

	int nZipLen = (int)fileZip.GetLength();
	m_pFileBuffer = new BYTE[nZipLen];
	fileZip.Read(m_pFileBuffer, nZipLen);
	fileZip.Close();

	m_hz = OpenZip(m_pFileBuffer, nZipLen, NULL);
	return TRUE;
}

int libzip::getItemSize(CString sFileName)
{
	int nZipIndex;
	ZIPENTRY ze;
	if (ZR_OK != FindZipItem(m_hz, sFileName, true, &nZipIndex, &ze)) {
		return 0;
	}
	return ze.unc_size;
}

BOOL libzip::loadItem(CString sFileName, BYTE* buff, int buff_size)
{
	int nZipIndex;
	ZIPENTRY ze;
	if (ZR_OK != FindZipItem(m_hz, sFileName, true, &nZipIndex, &ze)) {
		return FALSE;
	}
	if (ZR_OK != UnzipItem(m_hz, nZipIndex, buff, min(buff_size, ze.unc_size))) {
		return FALSE;
	}
	return TRUE;
}
